<template>
  <div class="chat-container">
    <!-- 聊天框左侧 - 历史对话记录 -->
    <div class="chat-history">
      <div class="history-header">
        <h3>历史对话</h3>
        <div class="button-group">
          <button class="new-chat-btn" @click="createNewChat">
            <span class="icon">➕</span> 新建
          </button>
          <button class="clear-btn" @click="clearHistory">
            <span class="icon">🗑️</span> 清空
          </button>
        </div>
      </div>
      <div class="theme-switcher">
        <span>主题：</span>
        <select v-model="selectedTheme" @change="switchTheme">
          <option value="light">浅色</option>
          <option value="dark">深色</option>
          <option value="blue">蓝色</option>
        </select>
      </div>
      <div class="current-chat-id">
        当前对话ID: <span class="chat-id">{{ currentChatId.substring(0, 8) }}...</span>
      </div>
      <div class="history-content">
        <div v-if="chatSessions.length" class="chat-sessions">
          <div v-for="session in chatSessions" 
               :key="session.id" 
               class="session-item"
               :class="{ active: session.id === currentChatId }"
               @click="switchSession(session.id)">
            <div class="session-title">
              {{ session.title || `对话 ${session.id.substring(0, 6)}...` }}
            </div>
            <div class="session-time">{{ formatDate(session.createdAt) }}</div>
          </div>
        </div>
        <template v-if="messageHistory.length">
          <div class="history-messages-title">当前对话记录</div>
          <div
            v-for="msg in messageHistory"
            :key="msg.id"
            class="history-item"
            :class="{ user: msg.role === 'user' }"
          >
            {{ msg.content.substring(0, 20)
            }}{{ msg.content.length > 20 ? "..." : "" }}
          </div>
        </template>
        <div v-else class="empty-history">暂无对话记录</div>
      </div>
    </div>

    <!-- 聊天框右侧 - 当前对话 -->
    <div class="chat-main">
      <!-- 对话内容区域 -->
      <div class="messages-container" ref="messagesContainer">
        <template v-if="messageHistory.length">
          <MessageItem
            v-for="msg in messageHistory"
            :key="msg.id"
            :message="msg"
            :theme="selectedTheme"
          />
        </template>
        <div v-else class="welcome-message">
          <div class="welcome-icon">👋</div>
          <h2>欢迎使用 AI 智能助手</h2>
          <p>请在下方输入框中输入您的问题，我会尽力为您解答。</p>
          <div class="feature-list">
            <div class="feature-item">
              <span class="feature-icon">💬</span>
              <span class="feature-title">自然对话</span>
              <span class="feature-desc">支持流畅的多轮对话</span>
            </div>
            <div class="feature-item">
              <span class="feature-icon">📝</span>
              <span class="feature-title">内容创作</span>
              <span class="feature-desc">帮助您创作各类文本内容</span>
            </div>
            <div class="feature-item">
              <span class="feature-icon">📊</span>
              <span class="feature-title">知识问答</span>
              <span class="feature-desc">解答您的各类知识问题</span>
            </div>
          </div>
        </div>
        <div v-if="loading && !isActiveMessageLoading" class="loading-indicator">
          <div class="loading-dots">
            <span></span>
            <span></span>
            <span></span>
          </div>
        </div>

        <!-- 添加调试展示，帮助查看消息列表 -->
        <div v-if="debugMode" class="debug-panel">
          <h4>调试信息：消息列表 ({{ messageHistory.length }}条)</h4>
          <div v-for="(msg, index) in messageHistory" :key="msg.id" class="debug-msg">
            <strong>{{ index }}. [{{ msg.role }}] {{ msg.id.substring(0, 8) }}...</strong>
            <span v-if="msg.loading"> (加载中)</span>
            <div class="debug-content">{{ msg.content.substring(0, 50) }}{{ msg.content.length > 50 ? '...' : '' }}</div>
          </div>
        </div>
      </div>

      <!-- 输入区域 -->
      <div class="input-container">
        <div class="input-wrapper">
          <textarea
            class="message-input"
            v-model="userInput"
            placeholder="请输入您的问题...（按 Ctrl+Enter 发送）"
            @keydown.enter.ctrl="sendMessage"
            :disabled="loading"
            ref="inputRef"
            rows="3"
          ></textarea>
          <div class="input-tools">
            <button class="tool-btn" title="上传文件" @click="uploadFile" :disabled="loading">
              <span class="icon">📎</span>
            </button>
            <button class="tool-btn" title="清空输入" @click="clearInput" :disabled="!userInput.trim() || loading">
              <span class="icon">✖️</span>
            </button>
            <button 
              class="tool-btn" 
              :title="debugMode ? '关闭调试' : '开启调试'" 
              @click="toggleDebug">
              <span class="icon">🛠️</span>
            </button>
          </div>
        </div>
        <div class="button-container">
          <button
            v-if="loading && isActiveStreamRequest"
            class="cancel-button"
            @click="cancelStreamRequest"
          >
            取消
          </button>
          <button
            class="send-button"
            @click="sendMessage"
            :disabled="!userInput.trim() || loading"
          >
            {{ loading ? "发送中..." : "发送" }}
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, nextTick, computed } from "vue";
import { useChatStore } from "../store/chat";
import MessageItem from "./MessageItem.vue";

// 获取聊天状态
const chatStore = useChatStore();
const { 
  messageHistory, 
  loading, 
  sendUserMessageStream, 
  cancelStreamRequest, 
  clearHistory,
  createNewChatSession,
  currentChatId,
  chatSessions,
  switchChatSession
} = chatStore;

// 主题设置
const selectedTheme = ref(localStorage.getItem('app_theme') || 'light');

// 用户输入
const userInput = ref("");
const inputRef = ref(null);
const messagesContainer = ref(null);
const isActiveStreamRequest = ref(false);

// 检查是否有正在加载中的消息
const isActiveMessageLoading = computed(() => {
  return messageHistory.value.some(msg => msg.loading);
});

// 开启调试模式
const debugMode = ref(false);

// 格式化日期
function formatDate(dateString) {
  if (!dateString) return '';
  const date = new Date(dateString);
  return date.toLocaleString('zh-CN', { 
    month: 'numeric', 
    day: 'numeric',
    hour: '2-digit', 
    minute: '2-digit'
  });
}

// 切换主题
function switchTheme() {
  // 主题切换逻辑
  document.body.setAttribute('data-theme', selectedTheme.value);
  // 保存主题设置到本地存储
  localStorage.setItem('app_theme', selectedTheme.value);
}

// 切换会话
function switchSession(sessionId) {
  if (sessionId === currentChatId.value) return;
  switchChatSession(sessionId);
}

// 上传文件
function uploadFile() {
  alert('文件上传功能即将上线');
}

// 清空输入
function clearInput() {
  userInput.value = "";
  inputRef.value.focus();
}

// 生成新的 chatId
function createNewChat() {
  const newChatId = createNewChatSession();
  console.log('新建对话，chatId:', newChatId);
}

// 发送消息 - 现在使用流式 API
async function sendMessage() {
  if (!userInput.value.trim() || loading.value) return;

  const message = userInput.value;
  userInput.value = "";
  isActiveStreamRequest.value = true;
  
  // 使用流式API发送消息，使用当前 chatId
  await sendUserMessageStream(message);
  
  // 自动聚焦输入框
  inputRef.value.focus();
  isActiveStreamRequest.value = false;
}

// 监听消息变化，滚动到底部
watch(
  messageHistory,
  async () => {
    await nextTick();
    if (messagesContainer.value) {
      messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight;
    }
  },
  { deep: true }
);

// 组件加载时初始化
onMounted(() => {
  inputRef.value.focus();
  switchTheme();
});

// 添加调试切换函数
function toggleDebug() {
  debugMode.value = !debugMode.value;
}
</script>

<style scoped>
.chat-container {
  display: flex;
  height: 85vh;
  min-height: 550px;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.1);
  background-color: #fff;
  border: 1px solid #eaeaea;
}

/* 左侧历史记录样式 */
.chat-history {
  width: 280px;
  background-color: #f0f2f5;
  display: flex;
  flex-direction: column;
  border-right: 1px solid #e8e8e8;
}

.history-header {
  padding: 16px;
  border-bottom: 1px solid #e8e8e8;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.history-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.button-group {
  display: flex;
  gap: 8px;
}

.clear-btn, .new-chat-btn {
  font-size: 12px;
  padding: 4px 8px;
  border-radius: 4px;
  cursor: pointer;
  display: flex;
  align-items: center;
  transition: all 0.3s;
}

.clear-btn {
  background-color: transparent;
  border: 1px solid #d9d9d9;
  color: #666;
}

.clear-btn:hover {
  color: #ff4d4f;
  border-color: #ff4d4f;
}

.new-chat-btn {
  background-color: #1890ff;
  color: white;
  border: none;
}

.new-chat-btn:hover {
  background-color: #40a9ff;
}

.icon {
  margin-right: 4px;
  font-size: 12px;
}

.theme-switcher {
  padding: 8px 16px;
  background-color: #eaeaea;
  display: flex;
  align-items: center;
  font-size: 13px;
}

.theme-switcher select {
  margin-left: 8px;
  padding: 4px;
  border-radius: 4px;
  border: 1px solid #d9d9d9;
}

.current-chat-id {
  padding: 8px 16px;
  font-size: 12px;
  color: #666;
  background-color: #eee;
  border-bottom: 1px solid #e8e8e8;
  word-break: break-all;
}

.chat-id {
  font-family: monospace;
  font-weight: bold;
  color: #1890ff;
}

.history-content {
  flex: 1;
  overflow-y: auto;
  padding: 12px;
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.chat-sessions {
  margin-bottom: 12px;
}

.session-item {
  padding: 10px;
  border-radius: 6px;
  background-color: #f9f9f9;
  margin-bottom: 8px;
  cursor: pointer;
  transition: all 0.3s;
  border: 1px solid transparent;
}

.session-item:hover {
  background-color: #e6f7ff;
}

.session-item.active {
  background-color: #e6f7ff;
  border-color: #91d5ff;
}

.session-title {
  font-weight: 500;
  font-size: 14px;
  margin-bottom: 4px;
  color: #333;
}

.session-time {
  font-size: 12px;
  color: #999;
}

.history-messages-title {
  font-size: 14px;
  font-weight: 500;
  margin: 8px 0;
  padding-bottom: 4px;
  border-bottom: 1px solid #eaeaea;
  color: #333;
}

.history-item {
  padding: 8px 12px;
  margin-bottom: 8px;
  border-radius: 6px;
  background-color: rgba(0, 0, 0, 0.03);
  cursor: pointer;
  font-size: 13px;
  color: #666;
  transition: background-color 0.3s;
}

.history-item.user {
  background-color: rgba(24, 144, 255, 0.1);
}

.history-item:hover {
  background-color: rgba(0, 0, 0, 0.06);
}

.empty-history {
  text-align: center;
  padding: 20px;
  color: #999;
  font-size: 14px;
}

/* 右侧聊天主区域样式 */
.chat-main {
  flex: 1;
  display: flex;
  flex-direction: column;
  background-color: #fff;
}

.messages-container {
  flex: 1;
  overflow-y: auto;
  padding: 24px;
  background-color: #fff;
  scroll-behavior: smooth;
}

.welcome-message {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  text-align: center;
  color: #333;
  padding: 20px;
}

.welcome-icon {
  font-size: 48px;
  margin-bottom: 20px;
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0% { transform: scale(1); }
  50% { transform: scale(1.1); }
  100% { transform: scale(1); }
}

.welcome-message h2 {
  margin-bottom: 12px;
  font-weight: 600;
  color: #1890ff;
}

.welcome-message p {
  max-width: 500px;
  line-height: 1.6;
  margin-bottom: 30px;
  color: #666;
}

.feature-list {
  display: flex;
  justify-content: center;
  gap: 20px;
  flex-wrap: wrap;
  margin-top: 20px;
}

.feature-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 150px;
  background-color: #f5f5f5;
  padding: 16px;
  border-radius: 10px;
  transition: transform 0.3s;
}

.feature-item:hover {
  transform: translateY(-5px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.1);
}

.feature-icon {
  font-size: 28px;
  margin-bottom: 8px;
}

.feature-title {
  font-weight: 600;
  margin-bottom: 6px;
  color: #1890ff;
}

.feature-desc {
  font-size: 12px;
  color: #666;
  text-align: center;
}

.loading-indicator {
  padding: 15px;
  text-align: center;
}

.loading-dots {
  display: inline-flex;
  align-items: center;
}

.loading-dots span {
  width: 8px;
  height: 8px;
  margin: 0 3px;
  background-color: #1890ff;
  border-radius: 50%;
  display: inline-block;
  animation: bounce 1.4s infinite ease-in-out both;
}

.loading-dots span:nth-child(1) {
  animation-delay: -0.32s;
}

.loading-dots span:nth-child(2) {
  animation-delay: -0.16s;
}

@keyframes bounce {
  0%,
  80%,
  100% {
    transform: scale(0);
  }
  40% {
    transform: scale(1);
  }
}

/* 输入区域样式 */
.input-container {
  border-top: 1px solid #e8e8e8;
  padding: 16px;
  display: flex;
  flex-direction: column;
  gap: 12px;
  background-color: #f9f9f9;
}

.input-wrapper {
  position: relative;
  display: flex;
  flex-direction: column;
}

.message-input {
  padding: 12px 16px;
  border: 1px solid #d9d9d9;
  border-radius: 8px;
  resize: none;
  font-family: inherit;
  font-size: 14px;
  line-height: 1.5;
  transition: all 0.3s;
}

.message-input:focus {
  outline: none;
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

.input-tools {
  position: absolute;
  right: 12px;
  bottom: 12px;
  display: flex;
  gap: 8px;
}

.tool-btn {
  background: none;
  border: none;
  cursor: pointer;
  width: 28px;
  height: 28px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s;
}

.tool-btn:hover {
  background-color: rgba(0, 0, 0, 0.06);
}

.tool-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.button-container {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.send-button {
  padding: 0 24px;
  height: 40px;
  border: none;
  border-radius: 6px;
  background-color: #1890ff;
  color: white;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s;
  font-weight: 500;
}

.send-button:hover {
  background-color: #40a9ff;
}

.send-button:disabled {
  background-color: #d9d9d9;
  cursor: not-allowed;
}

.cancel-button {
  padding: 0 20px;
  height: 40px;
  border: 1px solid #ff4d4f;
  border-radius: 6px;
  background-color: white;
  color: #ff4d4f;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s;
  font-weight: 500;
}

.cancel-button:hover {
  background-color: #fff1f0;
}

/* 深色主题支持 */
:global(body[data-theme="dark"]) .chat-container {
  background-color: #1f1f1f;
  border-color: #333;
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.3);
}

:global(body[data-theme="dark"]) .chat-history {
  background-color: #2a2a2a;
  border-right-color: #333;
}

:global(body[data-theme="dark"]) .history-header,
:global(body[data-theme="dark"]) .current-chat-id,
:global(body[data-theme="dark"]) .theme-switcher {
  border-bottom-color: #333;
  background-color: #252525;
  color: #ddd;
}

:global(body[data-theme="dark"]) .history-header h3 {
  color: #eee;
}

:global(body[data-theme="dark"]) .chat-main,
:global(body[data-theme="dark"]) .messages-container {
  background-color: #1f1f1f;
}

:global(body[data-theme="dark"]) .welcome-message h2 {
  color: #40a9ff;
}

:global(body[data-theme="dark"]) .welcome-message p {
  color: #bbb;
}

:global(body[data-theme="dark"]) .session-item {
  background-color: #252525;
}

:global(body[data-theme="dark"]) .session-item:hover {
  background-color: #2d3748;
}

:global(body[data-theme="dark"]) .session-item.active {
  background-color: #2d3748;
  border-color: #1890ff;
}

:global(body[data-theme="dark"]) .session-title {
  color: #eee;
}

:global(body[data-theme="dark"]) .history-item {
  background-color: rgba(255, 255, 255, 0.08);
  color: #ccc;
}

:global(body[data-theme="dark"]) .history-item.user {
  background-color: rgba(24, 144, 255, 0.2);
}

:global(body[data-theme="dark"]) .feature-item {
  background-color: #252525;
}

:global(body[data-theme="dark"]) .message-input {
  background-color: #2a2a2a;
  border-color: #333;
  color: #eee;
}

:global(body[data-theme="dark"]) .input-container {
  background-color: #252525;
  border-top-color: #333;
}

:global(body[data-theme="dark"]) .message-input:focus {
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.3);
}

/* 蓝色主题 */
:global(body[data-theme="blue"]) .chat-container {
  background-color: #f0f8ff;
  border-color: #d0e8ff;
}

:global(body[data-theme="blue"]) .chat-history {
  background-color: #e1f0ff;
  border-right-color: #c0dfff;
}

:global(body[data-theme="blue"]) .history-header,
:global(body[data-theme="blue"]) .current-chat-id,
:global(body[data-theme="blue"]) .theme-switcher {
  background-color: #d0e6ff;
  border-bottom-color: #c0dfff;
}

:global(body[data-theme="blue"]) .history-header h3 {
  color: #0050b3;
}

:global(body[data-theme="blue"]) .chat-main,
:global(body[data-theme="blue"]) .messages-container {
  background-color: #f0f8ff;
}

:global(body[data-theme="blue"]) .welcome-message h2 {
  color: #0050b3;
}

:global(body[data-theme="blue"]) .session-item {
  background-color: #e6f7ff;
}

:global(body[data-theme="blue"]) .session-item:hover {
  background-color: #bae7ff;
}

:global(body[data-theme="blue"]) .session-item.active {
  background-color: #bae7ff;
  border-color: #1890ff;
}

:global(body[data-theme="blue"]) .input-container {
  background-color: #e6f7ff;
  border-top-color: #d0e8ff;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .chat-container {
    flex-direction: column;
    height: 90vh;
  }

  .chat-history {
    width: 100%;
    height: 25vh;
    overflow-y: auto;
  }

  .chat-main {
    height: 65vh;
  }
}

.debug-panel {
  margin-top: 20px;
  padding: 10px;
  border: 1px dashed #999;
  background-color: #f8f8f8;
  border-radius: 8px;
  font-family: monospace;
  font-size: 12px;
}

.debug-panel h4 {
  margin: 0 0 10px;
  color: #666;
}

.debug-msg {
  margin-bottom: 6px;
  padding: 4px;
  border-bottom: 1px solid #eee;
}

.debug-content {
  margin-top: 4px;
  padding-left: 20px;
  color: #666;
  word-break: break-all;
}

.dark .debug-panel {
  background-color: #2d3748;
  border-color: #4a5568;
}

.dark .debug-panel h4,
.dark .debug-content {
  color: #a0aec0;
}

.dark .debug-msg {
  border-color: #4a5568;
}
</style>
